﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WS.EKA.Utility;
using WS.EKA.Business.Service;
using System.Threading.Tasks;
using WS.EKA.UI.Business;

namespace WS.EKA.Web.UI.Service
{
    //这里将服务端实例设置为单例，保证消息的顺序执行（默认情况下wcf的ConcurrencyMode=Single--单线程）
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class EventSourceMSMQ : IEventSourceMSMQ
    {
        public void SaveEventByString(string data)
        {
            Logger.Log("EventService Begining...");
            try
            {
                IService service = ServiceFactory.CreateService(ServiceType.EVENT.ToString());
                service.ImportData(data);
            }
            catch (Exception ex)
            {
                Logger.Log("EventService Error.");
                Logger.Log("Data:" + data);
                Logger.Error("EventService Error.", ex);
                Logger.Error("Data:" + data, null);
                //msmq can not send back because it's oneway
                //throw;
            }
            PushToClient();
            Logger.Log("EventService End.");
        }

        private void PushToClient()
        {
            Task.Factory.StartNew(() =>
            {
                ClientDataSourceBridge.PushEventToClient();

            }).ContinueWith(t =>
            {
                foreach (var inner in t.Exception.InnerExceptions)
                {
                    Logger.Error("Incident push Error.", inner);
                }
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
    }

    [ServiceContract]
    public interface IEventSourceMSMQ
    {
        [OperationContract(IsOneWay = true)]
        void SaveEventByString(string data);
    }
}
